package com.jiaai.web.live;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.jiaai.auth.model.AccessUser;
import com.jiaai.common.api.model.RPage;
import com.jiaai.exception.ErrorCode;
import com.jiaai.exception.ServerException;
import com.jiaai.filter.aop.TokenIntercept;

import com.jiaai.live.api.IAnchorApi;
import com.jiaai.live.api.ILiveApi;
import com.jiaai.live.api.IWatchHisApi;
import com.jiaai.live.exception.LiveStopException;
import com.jiaai.live.model.BLive;
import com.jiaai.live.model.RoomInfo;
import com.jiaai.live.model.VLiveReport;
import com.jiaai.util.*;
import com.jiaai.util.geograph.GeoHash;
import com.jiaai.util.geograph.LatLngDistance;
import com.jiaai.web.zfp.JMSProducer;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.jms.Destination;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * TODO
 * </p>
 *
 * @author 佳爱网络科技
 * @version V1.0
 * @title controller
 * @since 2017/10/11
 */
@SuppressWarnings("ALL")
@RestController
@RequestMapping("/api/v1/app/live")
public class LiveController {
    @Reference
    private ILiveApi liveApi;
    @Reference
    private IAnchorApi anchorApi;

    @Reference
    private IWatchHisApi iWatchHisApi;
    @Autowired
    private JMSProducer producer;

    /**
     * 手机播
     * @return
     * @throws ServerException
     */
    @GetMapping("/live/mobile")
    public  Object getLiveMobile(@RequestParam Integer curr
            , @RequestParam(required = false, defaultValue = "20") Integer pageSize)throws  ServerException{
        try {
            RPage obj = liveApi.getLiveMobile(curr, pageSize);
            return RestResultGenerator.genSuccessResult(obj.getRows()) ;
        }catch (Exception e){
            throw new ServerException("获取主播列表异常");
        }
    }

    /**
     * 开始直播并返回推流地址
     * @param accessUser
     * @param live
     * @return
     * @throws ServerException
     */
    @PostMapping("/start")
    @TokenIntercept
    public  Object startLive(@RequestBody BLive live)throws ServerException{
        AccessUser accessUser = RequestUtils.getUser();
        RoomInfo roomInfo=null;
        try {
            live.setmId(accessUser.getUserId());
             roomInfo=liveApi.startLive(live);
        }catch (Exception e){
            e.printStackTrace();
            return RestResultGenerator.genErrorResult("服务器异常");
        }
        try {
            Destination destination = new ActiveMQQueue("runRobot.queue");
            producer.runOrStopRobot(destination, "live_room_"+roomInfo.getLiveId());
        }catch (Exception e){

        }
        return RestResultGenerator.genSuccessResult(roomInfo);

    }

    /**
     *结束直播并返回本次直播报表
     * @param liveId
     * @return
     * @throws ServerException
     */
    @GetMapping("/stop/{liveId}")
    @TokenIntercept(checkVisitor = true)
    public RestResult<VLiveReport> stop(@PathVariable("liveId") Integer liveId)throws ServerException{
        try {
            AccessUser user = RequestUtils.getUser();
            VLiveReport obj = liveApi.stopLive(liveId, user.getUserId());
            //结算红包
            Destination destination = new ActiveMQQueue("completeHb.queue");
            producer.completeHb(destination, ""+liveId);

            return RestResultGenerator.genSuccessResult(obj);
        }catch (Exception e){
            e.printStackTrace();
            return RestResultGenerator.genErrorResult(e.getMessage());
        }

    }

    /**
     * 关注主播
     * @param live
     * @return
     * @throws ServerException
     */
    @GetMapping("/follow/{liveId}")
    @TokenIntercept(checkVisitor = true)
    public  Object followLive(@PathVariable("liveId") Integer live)throws ServerException{
         AccessUser user=RequestUtils.getUser();
         liveApi.followLive(live,user.getUserId());
         return RestResultGenerator.genSuccessResult();
    }

    @GetMapping("/follow/list")
    @TokenIntercept(checkVisitor = false)
    public  Object getMyFollowLives()throws ServerException{
        AccessUser user=RequestUtils.getUser();
        if(user==null){
            return RestResultGenerator.genSuccessResult();
        }else {
            return RestResultGenerator.genSuccessResult(liveApi.selectMyFollowLive(user.getUserId()));
        }
    }

    /**
     * 获取直播间祥情
     * @param liveId
     * @return
     * @throws ServerException
     */
    @GetMapping("/info/{liveId}")
    @TokenIntercept(checkVisitor = false)
    public  RestResult<Map<String,Object>> getLiveInfo(HttpServletRequest request
            , @PathVariable("liveId") Integer liveId)throws  ServerException{
        try {
            AccessUser user=RequestUtils.getUser();
             Map<String,Object> liveInfo=liveApi.getLiveInfo(liveId,user==null?"":user.getUserId());
             if(Integer.valueOf(liveInfo.get("status").toString())== LIVEStatus.ON.getType()){
                 Destination destination = new ActiveMQQueue("runRobot.queue");
                 producer.runOrStopRobot(destination, liveInfo.get("mId").toString()+"_"+liveInfo.get("liveId0"));
             }
             return  RestResultGenerator.genSuccessResult(liveInfo);
        } catch (Exception e) {
            if(e instanceof LiveStopException){
                return  RestResultGenerator.genErrorResult(ErrorCode.LIVE_ON_STOP,"live on stop");
            }else {
               throw  new ServerException("获取直播间祥情异常");
            }
        }
    }



    @GetMapping("/guard/list/{id}")
    @TokenIntercept
    public Object getGuardList(@PathVariable("id") String anchorId){
        try {
            return RestResultGenerator.genSuccessResult(liveApi.getGuardList(anchorId));
        }catch (Exception e){
            e.printStackTrace();
            return RestResultGenerator.genErrorResult("服务器异常");
        }

    }

    /**
     * 我的观看记录
     * @return
     */
    @GetMapping("/watchHis")
    @TokenIntercept
    public Object watchHis(){
        try {
            AccessUser user = RequestUtils.getUser();
            return RestResultGenerator.genSuccessResult(iWatchHisApi.getMyWatchHis(user.getUserId()));
        }catch (Exception e){
            e.printStackTrace();
            return RestResultGenerator.genErrorResult("服务器异常");
        }

    }

    /**
     * 我的直播记录
     * @param anchorId
     * @return
     */
    @GetMapping("/myLiveRecords")
    @TokenIntercept(checkVisitor = true)
    public Object myLiveRecords(){
        AccessUser user = RequestUtils.getUser();
        try {
            return RestResultGenerator.genSuccessResult(liveApi.getMyLiveRecords(user.getUserId()));
        }catch (Exception e){
            e.printStackTrace();
            return RestResultGenerator.genErrorResult("服务器异常");
        }

    }

    //踢人或禁言
    /**
     * targetId--------->对方的mId
     * @param type 1:踢人 2:禁言
     * @param anchorId
     * @param user ----操作人
     * @return
     */
    @PostMapping("/block")
    @TokenIntercept(checkVisitor = true)
    public Object block(@RequestParam Integer type, @RequestParam String anchorId
            , @RequestParam String targetId, @RequestParam String targetIdNo){
        AccessUser user = RequestUtils.getUser();
        //是否有权限踢人和禁言--->user对应于anchorId, 或者user是anchorId的守护
        if (!liveApi.canBlock(anchorId, user.getUserId())){
            return RestResultGenerator.genErrorResult("大爷的, 你没有权限");
        }

        boolean flag = liveApi.block(type,anchorId,  user.getUserId(), targetIdNo);
        if (flag){
            return RestResultGenerator.genSuccessResult("大爷的可以了");
        }else {
            return RestResultGenerator.genErrorResult("大爷的, 对方上头有人");
        }
    }


    /**
     * 直播间在线会员列表
     * @param liveId
     * @return
     */
    @GetMapping("/onlineMems/{liveId}")
    public Object onlineMems(@PathVariable Integer liveId){
        return RestResultGenerator.genSuccessResult(liveApi.getOnlineLiveMems(liveId));
    }

    /**
     * 退出直播间
     * @param liveId
     * @return
     */
    @PostMapping("/outLive/{liveId}")
    @TokenIntercept
    public Object outLive(@PathVariable Integer liveId){
        try {
            AccessUser user = RequestUtils.getUser();
            liveApi.outLiveHandle(liveId, user.getUserId());
            return RestResultGenerator.genSuccessResult("");
        }catch (Exception e){
            e.printStackTrace();
            return RestResultGenerator.genErrorResult("");
        }

    }

    /**
     * 附近直播
     * @param lat
     * @param lng
     * @return
     */
    @GetMapping("/near")
    public Object near( @RequestParam Double lat, @RequestParam Double lng){
        List<HashMap> list = liveApi.getNearLives(new GeoHash(lat, lng).getGeoHashBase32().substring(0,4));
        if (!CollectionsUtil.checkEmpty(list)){
            for (HashMap e : list){
                //客户端计算??
                JSONObject object = JSONObject.parseObject(e.get("latlng").toString());
                double eLat = object.getDoubleValue("lat");
                double eLng = object.getDoubleValue("lng");
                double dis = LatLngDistance.getDistance(lat, lng, eLat, eLng);
                e.put("distance", dis);
                e.remove("latlng");
            }
        }

        return RestResultGenerator.genSuccessResult(list);
    }

    /**
     * 加入直播间
     * @return
     * @throws ServerException
     */
    @GetMapping("/join/{liveid}")
    @TokenIntercept(checkVisitor = true)
    public  Object joinLiveRoom(@PathVariable("liveid") Integer liveId)throws ServerException{
            AccessUser accessUser=RequestUtils.getUser();
            return  RestResultGenerator.genSuccessResult(liveApi.joinLiveRoom(liveId,accessUser!=null?accessUser.getUserId():null));
    }

    /**
     *如果检查到上次直播异常退出则重新返回推流地址并直接开启直播
     * @return
     * @throws ServerException
     */
    @GetMapping("/lastLive")
    @TokenIntercept(checkVisitor = true)
    public  Object checkLastLiveStatus()throws  ServerException{
        AccessUser user = RequestUtils.getUser();
        RoomInfo roomInfo=liveApi.findLastOnLive(user.getUserId());
        Destination destination = new ActiveMQQueue("runRobot.queue");
        producer.runOrStopRobot(destination, "live_room_"+roomInfo.getLiveId());
        return RestResultGenerator.genSuccessResult(roomInfo);
    }
}
